<?php

namespace App\Services;

use App\Models\AgentConfig;

class AgentService
{
    public function saveAgentSettings($agentId, $settings)
    {
        \DB::transaction(function () use ($agentId, $settings) {
            AgentConfig::query()
                ->where('agent_id', $agentId)
                ->whereIn('config_key', array_keys($settings))
                ->delete();

            $insertValues = [];
            foreach ($settings as $key => $value) {
                $insertValues[] = [
                    'created_at' => now(),
                    'updated_at' => now(),
                    'agent_id' => $agentId,
                    'config_key' => $key,
                    'config_value' => $value ?: '',
                ];
            }
            AgentConfig::insert($insertValues);
        });
    }

    public function getAgentSettings($agentId, $keys)
    {
        return AgentConfig::query()
            ->where('agent_id', $agentId)
            ->whereIn('config_key', $keys)
            ->get()
            ->mapWithKeys(function (AgentConfig $config) {
                return [$config->config_key => $config->config_value];
            });
    }

    public function getAgentSetting($agentId, $key)
    {
        $config = AgentConfig::query()
            ->where('agent_id', $agentId)
            ->where('config_key', $key)
            ->first();

        if (!$config) {
            return null;
        }

        return $config->config_value;
    }
}
